package Tools;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import Plants.PowerPlant;

public class SmartGridFileReader {

	/**
	 * Populates the SmartGrid.allPlants map from an outside text file
	 * @param filename
	 * @return a map of power plants and their names
	 */
	public static Map<String, PowerPlant> populateSmartGridFromFile(String filename)
	{
		Map<String, PowerPlant> grid = new HashMap<String, PowerPlant>();
		FileInputStream fis;
		DataInputStream dis;
		BufferedReader br;
		String line;
		try 
		{	
			fis = new FileInputStream(filename);
			dis = new DataInputStream(fis);
			br = new BufferedReader(new InputStreamReader(dis));
			while( (line = br.readLine())  != null)
			{
				String[] data = line.split(";");
				PowerPlant p1 = grid.get(data[0]);  //check to see if power plant exists
				if(p1 == null)  //if not, create the plant
				{
					p1 = PowerPlantFactory.getPowerPlant(data[0], data[1]);
					grid.put(data[0], p1);
				}
				if(data.length > 2)  //check to see if the power plant is connected to something
				{
					PowerPlant p2 = grid.get(data[2]);
					if(p2 == null)
					{
						p2 = PowerPlantFactory.getPowerPlant(data[2], data[3]);
						grid.put(data[2], p2);
					}	
					p1.addPowerPlant(p2, Float.parseFloat(data[4]));
				}
			}
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.Write("Error in populate smart grid from file");
		}
		return grid;
	}
	
}
